﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CoreCms.Net.Utility.Helper
{
    public static class ChainHelper
    {
        //链金额精度
        public static Dictionary<string, decimal> money_accuracy = new Dictionary<string, decimal>()
        {
            {"LJZ", 100000000.00M},{"CIP", 100000000.00M},{"CIPC", 100000000.00M},{"TRX", 1000000.00M}
        };

        public static string HOST_LJZ = "http://39.108.163.223:8089";
        public static string HOST_CIP = "http://8.219.255.111:8081";

        #region 查询余额

        public static decimal GetBalance(string currency, string address, string coin = "LJZ")
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            decimal balance = 0;
            //判断余额  
            //老接口 /transaction/balance
            //新接口 /transaction/balance2
            string url = HOST.TrimEnd('/') + "/transaction/balance2?";
            url += "tokenSymbol=" + currency;
            url += "&address=" + address;
            if (!string.IsNullOrWhiteSpace(coin))
                url += "&chainName=" + coin;
            try
            {
                string result = HttpHelper.GetUrl(url);
                //Common._log.Info("请求接口：" + url + " 请求参数：   请求结果：" + result);
                //{"code":0,"msg":"success","data":[{"currency":0,"balance":0,"frozen":0,"addr":"1QAJDEFxDmovDRvMEtvXbthuxMcK3agS1x"}]}
                dynamic dyResult = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result);
                //ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);
                if (dyResult.code == 0)
                {
                    string accountString = Convert.ToString(dyResult.data).Trim('[').Trim(']');
                    ChainAccount resData = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainAccount>(accountString);
                    if (string.IsNullOrWhiteSpace(coin)) coin = "LJZ";
                    decimal accuracy = money_accuracy[coin];
                    balance = Convert.ToDecimal(resData.balance / accuracy);
                }
                else
                {
                    throw new Exception(dyResult.msg);
                }
            }
            catch { balance = 0; }

            return balance;
        }

        #endregion

        #region 构造交易

        public static string CreateTransfer(string currency, decimal total, string address, string send_address = "", string coin = "LJZ", bool deducLz = true)
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            if (!string.IsNullOrWhiteSpace(coin) && string.IsNullOrWhiteSpace(send_address))
                throw new Exception("发起交易地址参数异常");

            string url = HOST.TrimEnd('/') + "/transaction/create-raw-transaction";
            string coinKey = coin;
            if (string.IsNullOrWhiteSpace(coin)) coinKey = "LJZ";
            decimal accuracy = money_accuracy[coinKey];

            long money = Convert.ToInt64(total * accuracy);
            object jsonObj = new
            {
                tokenSymbol = currency,
                amount = money,
                toAddress = address,
                chainName = coin,
                fromAddress = send_address,
                deducLz = deducLz
            };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
            string result = HttpHelper.PostJson(url, json);
            //Common._log.Info("请求接口：" + url + " 请求参数：" + json + "  请求结果：" + result);
            ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);
            string hashString = string.Empty;
            if (chain.code != 0)
            {
                throw new Exception(chain.msg);
            }
            return "" + chain.data;
        }

        #endregion

        #region 构造交易 手续费版
        /// <summary>
        /// {

        /// </summary>
        /// <param name="from_address"></param>
        /// <param name="to_address"></param>
        /// <param name="total"></param>
        /// <param name="fee"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public static string CreateFeeTransfer(string token, decimal total, string from_address, string to_address, string fee_token, decimal fee, string fee_address, string coin = "LJZ")
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            if (!string.IsNullOrWhiteSpace(coin) && string.IsNullOrWhiteSpace(from_address) && string.IsNullOrWhiteSpace(to_address))
                throw new Exception("发起交易地址参数异常");

            string url = HOST.TrimEnd('/') + "/transaction/create-fee-raw-transaction";
            string coinKey = coin;
            if (string.IsNullOrWhiteSpace(coin)) coinKey = "LJZ";
            decimal accuracy = money_accuracy[coinKey];

            object jsonObj = new
            {
                chainName = coin,
                tokenSymbol = token,
                amount = Convert.ToInt64(total * accuracy),
                tokenFee = Convert.ToInt64(fee * accuracy),
                feeTokenSymbol = fee_token,
                receiveTokenFeeAddress = fee_address,
                toAddress = to_address,
                fromAddress = from_address
            };
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
            string result = HttpHelper.PostJson(url, json);
            //Common._log.Info("请求接口：" + url + " 请求参数：" + json + "  请求结果：" + result);
            ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);
            string hashString = string.Empty;
            if (chain.code != 0)
            {
                throw new Exception(chain.msg);
            }
            JArray jsonResponse = JArray.Parse("" + chain.data);
            foreach (var item in jsonResponse)
            {
                hashString += item + ",";
            }
            return hashString.Trim(',');
        }

        #endregion

        #region 交易上链

        public static string SendTransfer(string currency, string signString, string coin = "LJZ")
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            string url = HOST.TrimEnd('/') + "/transaction/send-transaction";
            object jsonObj = new { };
            if (string.IsNullOrWhiteSpace(coin))
            {
                jsonObj = new
                {
                    tokenSymbol = currency,
                    hexString = signString
                };
            }
            else
            {
                jsonObj = new
                {
                    tokenSymbol = currency,
                    hexString = signString,
                    chainName = coin
                };
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
            string result = HttpHelper.PostJson(url, json);
            //Common._log.Info("请求接口：" + url + " 请求参数：" + json + "  请求结果：" + result);
            ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);
            if (chain.code != 0)
                throw new Exception(chain.msg);
            return "" + chain.data;
        }

        #endregion

        #region 交易转账

        public static ChainRespon Transfer(string currency, decimal amount, string address, string apiKey, string coin = "LJZ")
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            string url = HOST.TrimEnd('/') + "/transaction/transfer";

            if (string.IsNullOrWhiteSpace(coin)) coin = "LJZ";
            decimal accuracy = money_accuracy[coin];

            long money = Convert.ToInt64(amount * accuracy);
            object jsonObj = new { };
            if (string.IsNullOrWhiteSpace(coin))
            {
                jsonObj = new
                {
                    tokenSymbol = currency,
                    amount = money,
                    toAddress = address,
                    merchantApiKey = apiKey
                };
            }
            else
            {
                jsonObj = new
                {
                    tokenSymbol = currency,
                    amount = money,
                    toAddress = address,
                    merchantApiKey = apiKey,
                    chainName = coin
                };
            }
            string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj);
            string result = HttpHelper.PostJson(url, json);
            //Common._log.Info("请求接口：" + url + " 请求参数：" + json + "  请求结果：" + result);
            ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);

            return chain;
        }

        #endregion

        #region 交易结果查询

        public static ChainRespon detail(string currency, string txHash, string coin = "LJZ")
        {
            string HOST = HOST_CIP;
            if (coin == "LJZ") HOST = HOST_LJZ;
            string url = HOST.TrimEnd('/') + "/transaction/tx-status?tokenSymbol=" + currency + "&txHash=" + txHash;
            if (!string.IsNullOrWhiteSpace(coin))
                url += "&chainName=" + coin;

            string result = HttpHelper.GetUrl(url);
            //Common._log.Info("请求接口：" + url + " 请求参数：   请求结果：" + result);
            ChainRespon chain = Newtonsoft.Json.JsonConvert.DeserializeObject<ChainRespon>(result);
            return chain;
        }

        #endregion


        #region 获取币价值

        public static decimal GetTokenPrice(string token, string coin = "CIPC")
        {
            //查询需要同步的币种 
            string url = "http://51.81.211.134:8082/interface/wallet-coin";
            Hashtable headht = new Hashtable();
            if (coin == "CIPC")
            {
                headht.Add("FZM-PLATFORM-ID", "1001");
                url = "http://51.81.211.134:8082/interface/wallet-coin";
            }
            else
            {
                headht.Add("FZM-PLATFORM-ID", "60");
                url = "http://182.160.9.60:8082/interface/wallet-coin";
            }
            List<string> list = new List<string>() { $"{token},{coin.ToLower()}" };
            var data = new
            {
                names = list
            };
            //序列号对象为json字符串
            string jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            //jsonStr = "{\"names\":[\"USDT,trx\"]}";
            string result = HttpHelper.PostJson(url, jsonStr, headht);

            dynamic dyResFst = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result);
            if (dyResFst.code != 0)
                throw new Exception(dyResFst.msg);

            List<dynamic> lstItem = Newtonsoft.Json.JsonConvert.DeserializeObject<List<dynamic>>("" + dyResFst.data);
            decimal price = decimal.Parse("" + lstItem[0].rmb);
            return price;
        }

        #endregion
    }


    public class ChainRespon
    {
        public int code { get; set; }
        public string msg { get; set; }
        public string data { get; set; }
    }
    public class ChainAccount
    {
        //{"code":0,"msg":"success","data":[{"currency":0,"balance":0,"frozen":0,"addr":"1QAJDEFxDmovDRvMEtvXbthuxMcK3agS1x"}]}
        public long currency { get; set; }
        public long balance { get; set; }
        public long frozen { get; set; }
        public string addr { get; set; }
    }
}
